package com.hutianao.gqgl.spring.auth;

import com.hutianao.gqgl.mybatis.entity.PtUserEntity;
import com.hutianao.gqgl.user.repository.UserDao;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
 
/**
 * 登陆失败监听
 */
@Component
public class AuthenticationFailureListener implements ApplicationListener<AuthenticationFailureBadCredentialsEvent> {

    private Logger logger = LogManager.getLogger(this.getClass());

    @Autowired
    private UserDao userDao;

    @Value("${max_error_num}")
    private Integer max_error_num;
    Map<String,Integer> map = new HashMap<>();

    @Override
    public void onApplicationEvent(AuthenticationFailureBadCredentialsEvent authenticationFailureBadCredentialsEvent) {
        logger.info("用户登录失败，进入监听器");
        String account = authenticationFailureBadCredentialsEvent.getAuthentication().getPrincipal().toString();
        PtUserEntity ptUserEntity  = userDao.queryUserInfoByName(account);
        if(ptUserEntity!=null){
            if(ptUserEntity.getIsSum()!=null && ptUserEntity.getIsSum()==0){
                // 锁定用户，直接修改时间
                userDao.updateTimeByAccount(account,new Date());
            }else{
                int num = map.getOrDefault(account,0);
                if(num+1<=max_error_num){
                    // 没有超出，则用hashmap记录,同时更新map
                    userDao.updateTimeByAccount(account,new Date());
                    map.put(account,num+1);
                }else{
                    // 超出直接锁定
                    userDao.updateStatusByAccount(account, new Date(),0);
                    map.remove(account);
                }
            }
        }
    }
}
